package com.example.amusic.utils

import android.annotation.SuppressLint
import android.content.ContentUris
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import androidx.annotation.OptIn
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.core.net.toUri
import androidx.core.os.bundleOf
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi
import coil.ImageLoader
import com.example.amusic.bean.SongBean
import com.example.amusic.db.SongEntity

//fun Cursor.toSongBean(): SongBean? {
//    val dataIndex = getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)
//    val idIndex = getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
//    val data = getString(dataIndex)
//    val id = getLong(idIndex)
//    return
//}

fun getAlbumArt(albumId: Long): Uri {
    val sArtworkUri = "content://media/external/audio/albumart".toUri()
    return ContentUris.withAppendedId(sArtworkUri, albumId)
}

const val IS_LOCAL_KEY = "isLocal"
const val EXTRA_BASE_COVER = "base_cover"
const val EXTRA_DURATION = "duration"
const val EXTRA_FILE_PATH = "file_path"
const val EXTRA_FILE_NAME = "file_name"
const val EXTRA_FILE_SIZE = "file_size"

val SongBean.asMediaItem: MediaItem
    @SuppressLint("UnsafeOptInUsageError")
    get() = MediaItem.Builder().setMediaMetadata(
        MediaMetadata.Builder().setTitle(songName).setArtist(artistName).setArtworkUri(coverUrl)
            .setExtras(
                bundleOf(IS_LOCAL_KEY to true)
            ).build()
    ).setUri(id).setMediaId(id).setCustomCacheKey(id).build()

fun generateUniqueId(type: Int, songId: Long): String {
    return "$type#$songId"
}


fun MediaMetadata.Builder.setBaseCover(value: String) = apply {
    val extras = build().extras ?: bundleOf()
    extras.putString(EXTRA_BASE_COVER, value)
    setExtras(extras)
}

fun MediaMetadata.Builder.setDuration(duration: Long) = apply {
    val extras = build().extras ?: bundleOf()
    extras.putLong(EXTRA_DURATION, duration)
    setExtras(extras)
}

fun MediaMetadata.Builder.setFilePath(value: String) = apply {
    val extras = build().extras ?: bundleOf()
    extras.putString(EXTRA_FILE_PATH, value)
    setExtras(extras)
}

fun MediaMetadata.Builder.setFileName(name: String) = apply {
    val extras = build().extras ?: bundleOf()
    extras.putString(EXTRA_FILE_NAME, name)
    setExtras(extras)
}

fun MediaMetadata.Builder.setFileSize(size: Long) = apply {
    val extras = build().extras ?: bundleOf()
    extras.putLong(EXTRA_FILE_SIZE, size)
    setExtras(extras)
}

fun SongEntity.toMediaItem(): MediaItem {
    return MediaItem.Builder()
        .setMediaId(uniqueId)
        .setUri(uri)
        .setMediaMetadata(
            MediaMetadata.Builder()
                .setTitle(title)
                .setArtist(artist)
                .setAlbumTitle(album)
                .setAlbumArtist(artist)
                .setArtworkUri(Uri.parse(getLargeCover()))
                .setBaseCover(albumCover)
                .setDuration(duration)
                .setFilePath(path)
                .setFileName(fileName)
                .setFileSize(fileSize)
                .build()
        )
        .build()
}

fun MediaItem.getSongType(): Int {
    return mediaId.split("#").firstOrNull()?.toIntOrNull() ?: SongEntity.LOCAL
}

fun MediaItem.isLocal(): Boolean {
    return getSongType() == SongEntity.LOCAL
}

fun MediaItem.getSmallCover(): String {
    val baseCover = mediaMetadata.getBaseCover()
    return if (isLocal()) {
        baseCover ?: ""
    } else {
        baseCover?.asSmallCover() ?: ""
    }
}

fun MediaMetadata.getBaseCover(): String? {
    return extras?.getString(EXTRA_BASE_COVER)
}

fun String.asSmallCover(): String {
    return appendImageSize(200)
}

fun String.asLargeCover(): String {
    return appendImageSize(800)
}

private fun String.appendImageSize(size: Int): String {
    return if (contains("?")) {
        "$this&param=${size}y${size}"
    } else {
        "$this?param=${size}y${size}"
    }
}

val LocalEfficientThumbnailImageLoader =
    staticCompositionLocalOf<ImageLoader> { throw IllegalStateException() }